package presentation.web;

import jaxcent.HtmlButton ;
import jaxcent.HtmlInputCheckbox ;
import jaxcent.HtmlInputPassword ;
import jaxcent.HtmlInputRadio ;
import jaxcent.HtmlInputText ;
import jaxcent.HtmlPara ;
import jaxcent.HtmlSelect ;
import jaxcent.Jaxception ;
import util.DuplicationException ;

/**
 * page for new member registration.
 *
 * @author Hadas
 */
public class RegisterPage extends MainPage
{

	/** The username text field. */
	private HtmlInputText username;

	/** The password text field. */
	private HtmlInputPassword pass;

	/** The pass verify text field. */
	private HtmlInputPassword passVerify;

	/** The first name text field. */
	private HtmlInputText firstName;

	/** The last name text field. */
	private HtmlInputText lastName;

	/** The residence text field. */
	private HtmlInputText residence;

	/** The male gender. */
	private HtmlInputRadio maleGender;

	/** The female gender. */
	private HtmlInputRadio femaleGender;

	/** The birth day check box. */
	private HtmlInputCheckbox birthDayCheckBox;

	/** The day of birthday. */
	private HtmlSelect birthDay;

	/** The month of birthday. */
	private HtmlSelect birthMonth;

	/** The year of birthday. */
	private HtmlSelect birthYear;

	/** The errors paragraph s error messages to user. */
	private HtmlPara errorsPara;

	/**
	 * Instantiates a new register page.
	 *
	 */
	public RegisterPage()
	{
		super();
		try
		{
			this.username = new HtmlInputText(this,"name");
			this.pass = new HtmlInputPassword(this,"pass");
			this.passVerify = new HtmlInputPassword(this,"passVerify");
			this.firstName = new HtmlInputText(this,"firstName");
			this.lastName = new HtmlInputText(this,"lastName");
			this.residence = new HtmlInputText(this,"residence");
			this.femaleGender = new HtmlInputRadio(this,"femaleGender");
			this.maleGender = new HtmlInputRadio(this,"maleGender");
			this.setErrors();
			this.makeButton();
			this.createBirthdaySelect();
		}
		catch (Exception e)
		{
			this.navigateToErrorPage(e, null);
		}
	}


	/**
	 * Check box birthday handler.
	 * Determine what's happen when the user choose the birthday check box
	 */
	protected void checkBoxBirthdayHandler()
	{
		try
		{	//if checked -> make unchecked
			if(this.birthDayCheckBox.getChecked())
			{
				this.birthDayCheckBox.setChecked(false);
				this.setSelected(true);	
			}
			else
			{
				this.birthDayCheckBox.setChecked(true);
				this.setSelected(false);
			}
		}
		catch (Exception e)
		{
			this.navigateToErrorPage(e, this.birthDayCheckBox);
		}

	}

	/**
	 * Register button handler.
	 * Handles pressing the register button including all corresponding domain services
	 * like registering to the forum etc.
	 */
	protected void htmlButtonHandler()
	{
		try
		{
			this.errorsPara.setInnerHTML("");
			/*reading from html page all necessary information */
			String uName = this.username.getValue();
			String password = this.pass.getValue();
			String verifyPassword = this.passVerify.getValue();
			//checks if one of the obligatory fields is empty
			if((uName.equals(""))||(password.equals("")) ||(verifyPassword.equals("")))
			{
				this.errorsPara.setInnerHTML("Missing username or password!");
				this.username.setValue("");
				this.pass.setValue("");
				this.passVerify.setValue("");
			}
			//checks if password and verify pass is match
			else if(password.equals(verifyPassword))
			{
				String fName = this.firstName.getValue();
				String lName = this.lastName.getValue();
				String habitation = this.residence.getValue();
				String gender = "";
				String dateOfBirth = "";
				//check gender
				if(this.femaleGender.getChecked())
				{
					gender = "Female";
				}
				else if(this.maleGender.getChecked())
				{
					gender="Male";
				}

				if(this.birthDayCheckBox.getChecked()){
					String day = this.birthDay.getOption(this.birthDay.getSelectedIndex()).getValue();
					String month = this.birthMonth.getOption(this.birthMonth.getSelectedIndex()).getValue();
					String year = this.birthYear.getOption(this.birthYear.getSelectedIndex()).getValue();
					if(!this.checkDateCorrectness(day,month))
					{
						this.errorsPara.setInnerHTML("Invalid date, correct and register again.");
						return;
					}
					dateOfBirth = day+"/"+month+"/"+year;
				}
				//register with all details
				this.getForumLogic().register(uName, password,fName,lName,dateOfBirth,gender,habitation);
				this.errorsPara.setStyle("color", "blue");
				this.errorsPara.setInnerHTML("Register successful");
				this.pageWait();
				this.navigateToPage(MainPage.HOME_PAGE) ;
			}
			else
			{
				this.errorsPara.setInnerHTML("Password verification doesn't match, Please type again.");
				this.pass.setValue("");
				this.passVerify.setValue("");
			}
		}
		catch (DuplicationException e)
		{
			try
			{
				this.errorsPara.setInnerHTML("Username already exists, Choose another");
				this.username.setValue("");
				this.pass.setValue("");
				this.passVerify.setValue("");
			}
			catch (Jaxception e1)
			{
				this.navigateToErrorPage(e1, null);
			}
		}
		catch (Exception e)
		{
			this.navigateToErrorPage(e, null) ;
		}
	}

	/**
	 * Check date correctness.
	 *
	 * @param day the day
	 * @param month the month
	 *
	 * @return true, if date is correct
	 */
	private boolean checkDateCorrectness(final String day,final String month)
	{
		try
		{
			if(month.equals("2") && Integer.parseInt(day)> 28)
			{
				return false;
			}
			if(((month.equals("11")) || (month.equals("6"))|| (month.equals("4"))|| (month.equals("9"))) && Integer.parseInt(day)> 30)
			{
				return false;
			}
		}
		catch (Exception e)
		{
			this.navigateToErrorPage(e, null) ;
		}
		return true;
	}

	/**
	 * Creates the birthday select. Include the birthday check box
	 * Creates correspond onClick birthday handler
	 * Initialize the dates
	 */
	private void createBirthdaySelect()
	{
		try
		{
			this.birthDay = new HtmlSelect(this,"birthDay");
			this.birthMonth = new HtmlSelect(this,"birthMonth");
			this.birthYear = new HtmlSelect(this,"birthYear");
			this.setSelected(true);
			this.birthDayCheckBox = new HtmlInputCheckbox(this, "dateBirth"){
				@Override protected void onClick(){
					RegisterPage.this.checkBoxBirthdayHandler();
				}
			};
		}
		catch(Exception e)
		{
			this.navigateToErrorPage(e, null);
		}
		try
		{
			this.birthDayCheckBox.setEnabled(true);
			this.birthDayCheckBox.setChecked(false);
			//Init days
			for(int i=1; i<=31;i++){
				this.birthDay.insertOption(i, Integer.toString(i));
			}
			//Init months
			for(int i=1; i<=12;i++){
				this.birthMonth.insertOption(i, Integer.toString(i));
			}
			//Init years
			int j = 1;
			for(int i=2009; i>=1950;i--){
				this.birthYear.insertOption(j, Integer.toString(i));
				j++;
			}
		}
		catch(Exception e)
		{
			this.navigateToErrorPage("Error in date component", null);
		}

	}

	/**
	 * Create register button.
	 * Create correspond override onClick method
	 */
	private void makeButton(){
		try
		{
			new HtmlButton(this,"register"){
		        @Override protected void onClick(){
		        	RegisterPage.this.htmlButtonHandler();
		        }
		    };
		}
		catch(Exception e)
		{
			this.navigateToErrorPage(e, null);
		}
	}

	/**
	 * Make the current page wait for 2 second for user to see the message on screen.
	 */
	private void pageWait()
	{
		try
		{
			Thread.sleep(2000);
		}
		catch (InterruptedException e)
		{
			//interrupt the page before 2000 mili is ok
		}
		catch(Exception e)
		{
			this.navigateToErrorPage(e, null);
		}
	}

	/**
	 * Sets the errors paragraph with initialize empty text.
	 */
	private void setErrors()
	{
		try
		{
			this.errorsPara = new HtmlPara(this,"paraError");
			this.errorsPara.setInnerHTML("");
		}
		catch (Exception e)
		{
			this.navigateToErrorPage(e, this.errorsPara);
		}
	}

	/**
	 * Sets disabled/enabled for all date component.
	 *
	 * @param par boolean which determine disabled or enabled
	 */
	private void setSelected(final boolean par)
	{
		try
		{
			this.birthDay.setDisabled(par);
			this.birthMonth.setDisabled(par);
			this.birthYear.setDisabled(par);
		}
		catch (Exception e)
		{
			this.navigateToErrorPage("Error in date component", null);
		}
	}
	

	/* (non-Javadoc)
	 * @see presentation.web.MainPage#onLoad()
	 */
	/**
	 * Initialize the date fields 
	 */
	@Override
	protected void onLoad()
	{
		super.onLoad();
		try
		{
			this.birthDay.setSelectedIndex(0);
			this.birthMonth.setSelectedIndex(0);
			this.birthYear.setSelectedIndex(0);
		}
		catch (Exception e)
		{
			this.navigateToErrorPage(e, this.birthDay);
		}
	}
}
